﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.IO;

namespace MSPathFinderTool
{
    class Program
    {
        static void Main(string[] args)
        {
            DBTool tool = new DBTool();
            DirectoryInfo TheFolder=new DirectoryInfo(@"E:\VSWork\MSPathFinder\ms-roomlocator\MSPathFinder\Content\PlanPath");

            //tool.GenerateBuildingData();
            foreach (FileInfo NextFile in TheFolder.GetFiles())
            {
                tool.GeneratePlanPathData(NextFile.FullName);
            }

            //tool.GeneratePlanPathData(@"E:\VSWork\MSPathFinder\ms-roomlocator\MSPathFinder\Content\PlanPath\114f2.xml");
            Console.ReadLine();
        }
    }

    class DBTool
    {
        public DBTool()
        {

        }

        public void ShortenFileSize(XDocument xDoc, string groupName)
        {
            var backgroundGroup = from g in xDoc.Descendants(XName.Get("g", "http://www.w3.org/2000/svg"))
                                  where g.Attribute("id").Value == groupName
                                  select g;
            foreach (var p in backgroundGroup.Descendants(XName.Get("path", "http://www.w3.org/2000/svg")))
            {
                string data = p.Attribute("d").Value.Replace("M ", "M").Replace("L ", "L");
                StringBuilder sb = new StringBuilder();
                foreach (string s in data.Split(' '))
                {
                    if (s.StartsWith("M") || s.StartsWith("L"))
                    {
                        double x = double.Parse(s.Split(',')[0].Substring(1));
                        double y = double.Parse(s.Split(',')[1]);
                        sb.Append(string.Format("{0}{1},{2} ", s.Substring(0, 1), x.ToString("0"), y.ToString("0")));
                    }
                    else
                    {
                        sb.Append(s + " ");
                    }
                }

                p.SetAttributeValue("d", sb.ToString());
                p.SetAttributeValue("class", null);
            }
        }

        public void GeneratePlanPathData(string filename)
        {
            XDocument xDoc = XDocument.Load(filename);
            this.ShortenFileSize(xDoc, "rooms");
            this.GetBoundaryOfGroupPath(xDoc, "rooms");
            var backgroundGroup = from g in xDoc.Descendants(XName.Get("g", "http://www.w3.org/2000/svg"))
                                  where g.Attribute("id").Value == "background"
                                  select g;
            backgroundGroup.FirstOrDefault().Remove();
            xDoc.Save(filename.Replace("PlanPath", "PlanPathR"));
        }

        public void GetBoundaryOfGroupPath(XDocument xDoc, string groupName)
        {
            double minX = 950, minY = 900, maxX = 0, maxY = 0; 
            var backgroundGroup = from g in xDoc.Descendants(XName.Get("g", "http://www.w3.org/2000/svg"))
                                  where g.Attribute("id").Value == groupName
                                  select g;
            foreach (var p in backgroundGroup.Descendants(XName.Get("path", "http://www.w3.org/2000/svg")))
            {
                double minTileX = 950, minTileY = 900, maxTileX = 0, maxTileY = 0;
                string data = p.Attribute("d").Value;
                foreach (string s in data.Split(' '))
                {
                    if (!s.StartsWith("M") && !s.StartsWith("L")) continue;
                    double x = double.Parse(s.Split(',')[0].Substring(1));
                    double y = double.Parse(s.Split(',')[1]);
                    if (minTileX >= x)
                    {
                        minTileX = x;
                    }
                    if (maxTileX <= x)
                    {
                        maxTileX = x;
                    }
                    if (minTileY >= y)
                    {
                        minTileY = y;
                    }
                    if (maxTileY <= y)
                    {
                        maxTileY = y;
                    }

                    if (minX > minTileX)
                    {
                        minX = minTileX;
                    }
                    if (maxX < maxTileX)
                    {
                        maxX = maxTileX;
                    }
                    if (minY > minTileY)
                    {
                        minY = minTileY;
                    }
                    if (maxY < maxTileY)
                    {
                        maxY = maxTileY;
                    }
                }

                p.SetAttributeValue("x1", minTileX.ToString("0"));
                p.SetAttributeValue("y1", minTileY.ToString("0"));
                p.SetAttributeValue("x2", maxTileX.ToString("0"));
                p.SetAttributeValue("y2", maxTileY.ToString("0"));
            }

            backgroundGroup.FirstOrDefault().SetAttributeValue("x1", minX.ToString("0"));
            backgroundGroup.FirstOrDefault().SetAttributeValue("y1", minY.ToString("0"));
            backgroundGroup.FirstOrDefault().SetAttributeValue("x2", maxX.ToString("0"));
            backgroundGroup.FirstOrDefault().SetAttributeValue("y2", maxY.ToString("0"));
        }

        #region Database operations
        public void GenerateBuildingXmlData()
        {
            string conn = @"Data Source=.\SQLEXPRESS;AttachDbFilename=E:\VSWork\WebAppStore\MSPathFinder\MSPathFinderTool\Database.mdf;Integrated Security=True;User Instance=True";
            using (DataClassesDataContext dcdc = new DataClassesDataContext(conn))
            {
                XDocument xdoc = new XDocument();
                xdoc.Add(new XElement("Root"));

                foreach (var r in dcdc.Buildings)
                {
                    XElement building = new XElement("Building");
                    building.SetAttributeValue("ID", r.ID.ToString());
                    building.SetAttributeValue("Name", r.Name);
                    building.SetAttributeValue("Address", r.Address);
                    building.SetAttributeValue("Latitude", r.Latitude.ToString());
                    building.SetAttributeValue("Longitude", r.Longitude.ToString());
                    building.SetAttributeValue("TopLeftLatitude", r.TopLeftLatitude.ToString());
                    building.SetAttributeValue("TopLeftLongitude", r.TopLeftLongitude.ToString());
                    building.SetAttributeValue("BottomRightLatitude", r.BottomRightLatitude.ToString());
                    building.SetAttributeValue("BottomRightLongitude", r.BottomRightLongitude.ToString());
                    xdoc.Root.Add(building);
                }

                xdoc.Save("Buildings.xml");
            }
        }

        public void GenerateRoomXmlData()
        {
            string conn = @"Data Source=.\SQLEXPRESS;AttachDbFilename=E:\VSWork\WebAppStore\MSPathFinder\MSPathFinderTool\Database.mdf;Integrated Security=True;User Instance=True";
            using (DataClassesDataContext dcdc = new DataClassesDataContext(conn))
            {
                XDocument xdoc = new XDocument();
                xdoc.Add(new XElement("Root"));

                foreach (var r in dcdc.Rooms)
                {
                    XElement room = new XElement("Room");
                    room.SetAttributeValue("ID", r.ID.ToString());
                    room.SetAttributeValue("Name", r.Name);
                    room.SetAttributeValue("Building", r.Building);
                    room.SetAttributeValue("Alias", r.Alias);
                    room.SetAttributeValue("OffsetX", r.OffsetX.ToString());
                    room.SetAttributeValue("OffsetY", r.OffsetX.ToString());
                    room.SetAttributeValue("LabAccount", r.LabAccount);
                    room.SetAttributeValue("Floor", r.Floor.ToString());
                    room.SetAttributeValue("FloorPlan", r.FloorPlan);
                    xdoc.Root.Add(room);
                }

                xdoc.Save("Rooms.xml");
            }
        }

        public void WriteInfoDatabase()
        {
            string conn = @"Data Source=.\SQLEXPRESS;AttachDbFilename=E:\VSWork\WebAppStore\MSPathFinder\MSPathFinderTool\Database.mdf;Integrated Security=True;User Instance=True";
            using (DataClassesDataContext dcdc = new DataClassesDataContext(conn))
            {
                dcdc.Buildings.DeleteAllOnSubmit(dcdc.Buildings);
                XDocument xdoc = XDocument.Load("Buildings.xml");
                
                foreach (var b in xdoc.Descendants("Building"))
                {
                    // write into database
                    Building building = new Building()
                    {
                        Address = b.Attribute("Address").Value,
                        BottomRightLatitude = float.Parse(b.Attribute("BottomRightLatitude").Value),
                        BottomRightLongitude = float.Parse(b.Attribute("BottomRightLongitude").Value),
                        TopLeftLatitude = float.Parse(b.Attribute("TopLeftLatitude").Value),
                        TopLeftLongitude = float.Parse(b.Attribute("TopLeftLongitude").Value),
                        Latitude = float.Parse(b.Attribute("TopLeftLongitude").Value),
                        Longitude = float.Parse(b.Attribute("TopLeftLongitude").Value),
                        Name = b.Attribute("Name").Value
                    };

                    dcdc.Buildings.InsertOnSubmit(building);
                }

                dcdc.SubmitChanges();
            }
        }

        public void WritePlanPathDatabase()
        {
            string conn = @"Data Source=.\SQLEXPRESS;AttachDbFilename=E:\VSWork\WebAppStore\MSPathFinder\MSPathFinderTool\Database.mdf;Integrated Security=True;User Instance=True";
            using (DataClassesDataContext dcdc = new DataClassesDataContext(conn))
            {
                FloorPlan floorPlan = new FloorPlan()
                {
                    Building = "115",
                    Floor = 1
                };

                dcdc.FloorPlans.InsertOnSubmit(floorPlan);
                dcdc.SubmitChanges();

                XDocument xdoc = XDocument.Load("Data/115.xml");
                foreach (var b in xdoc.Descendants("path"))
                {
                    PlanPath path = new PlanPath()
                    {
                        Data = b.Attribute("d").Value,
                        FloorPlanID = floorPlan.ID
                    };

                    dcdc.PlanPaths.InsertOnSubmit(path);
                }

                foreach (var b in xdoc.Descendants("circle"))
                {
                    PlanCircle path = new PlanCircle()
                    {
                        CR = float.Parse(b.Attribute("r").Value),
                        CX = float.Parse(b.Attribute("cx").Value),
                        CY = float.Parse(b.Attribute("cy").Value),
                        FloorPlanID = floorPlan.ID
                    };

                    dcdc.PlanCircles.InsertOnSubmit(path);
                }

                dcdc.SubmitChanges();
            }
        }
        #endregion
    }
}
